package net.sinodata.smartframework.component;

import net.sinodata.smartframework.entity.QueueThreadPool;
import net.sinodata.smartframework.service.QueueThreadPoolService;
import net.sinodata.smartframework.threadpool.base.QueueThreadPoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Description: 线程池启动类
 * 
 * @author: yinliangyun
 * @date: 2021-5-18
 */
@Component
@Order(value = 2)
public class QueueThreadPoolRunner implements ApplicationRunner {

	private static final Logger logger = LoggerFactory.getLogger(QueueThreadPoolRunner.class);
	
	@Autowired
	private QueueThreadPoolService queueThreadPoolService;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("QueueThreadPoolRunner run start");

		// 查询数据库表queue_thread_pool中所有数据
		List<QueueThreadPool> queueThreadPoolList = queueThreadPoolService.list();
		logger.info("QueueThreadPoolRunner run queueThreadPoolList size : {}", queueThreadPoolList.size());
		
		for (QueueThreadPool queueThreadPool : queueThreadPoolList) {
			logger.info("QueueThreadPoolRunner run queueThreadPool : {}", queueThreadPool);
			try {
				// 调用队列线程池管理类初始化线程池
				QueueThreadPoolManager.getInstance().startThreadPool(queueThreadPool.getQueueName(),
						queueThreadPool.getQueueCode(),
						queueThreadPool.getQueueClass(),
						QueueThreadPoolManager.getProcessClass(queueThreadPool.getQueueClass()),
						queueThreadPool.getThreadSize(),
						queueThreadPool.getRunStartTime(),
						queueThreadPool.getRunEndTime(),
						queueThreadPool.getWaitTime());
			} catch (Exception e) {
				logger.error("QueueThreadPoolRunner run exception queueThreadPool : {}", queueThreadPool + "_" + e.getMessage(), e);
				throw e;
			}
		}
		
		// 获取初始化成功后的线程池个数
		int queueThreadPoolSize = QueueThreadPoolManager.getInstance().getQueueThreadPoolSize();
		logger.info("QueueThreadPoolRunner run end alive queueThreadPoolSize : {}", queueThreadPoolSize);
	}
	
}
